import 'dart:ui';
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart ';
import 'package:flutter/rendering.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:flutter/services.dart';
import '../user_data.dart';

import '../constants.dart' show Constants, AppColors;

import './conversation_page.dart';
import './contacts_page.dart';
import './kunpeng_page.dart';

// 枚举的方式
enum ActionItems { GROUP_CHAT, ADD_FRIEND, QR_SCAN, PAYMENT }

class NavigationIconView {
  // 暴露BottomNavigationBarItem
  final BottomNavigationBarItem item;

  NavigationIconView(
      {Key key, String title, IconData icon, IconData activeIcon})
      : item = BottomNavigationBarItem(
          icon: Icon(
            icon,
          ),
          activeIcon: Icon(
            activeIcon,
          ),
          title: Text(
            title,
          ),
          backgroundColor: Colors.white,
        );
}

class HomeScreen extends StatefulWidget {
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  PageController _pageController;
  // 当前页面索引值
  int _currentIndex = 0;
  List<NavigationIconView> _navigationViews;
  // 定义要显示页面的集合
  List<Widget> _pages;

  // 初始化的状态
  void initState() {
    super.initState();
    // 初始化SDK
    RongIMClient.init(RongAppKey);

    // 状态监听（监听SDK与融云服务器连接的状态）
    RongIMClient.onConnectionStatusChange = (int connectionStatus) {
      if (RCConnectionStatus.KickedByOtherClient == connectionStatus ||
          RCConnectionStatus.TokenIncorrect == connectionStatus ||
          RCConnectionStatus.UserBlocked == connectionStatus) {
        String toast = "连接状态变化 $connectionStatus ,请退出后重新登录";
        print('$toast');
      } else if (RCConnectionStatus.Connected == connectionStatus) {
        // ignore: deprecated_member_use
        UpdateLiveRegionEvent();
        print('连接成功');
      }
    };

    // 连接
    RongIMClient.connect(RongIMToken, (int code, String userId) {
      print('连接结果' + code.toString());
      if (code == 0) {
        print('连接成功 userId：' + userId);
        // 连接成功后打开数据库
        // _initUserInfoCache();
      } else if (code == 31004) {
        print('token无效，需要重新从APP服务器获取新的 token 并连接');
      }
    });

    // 底部tabBar图标及图标名称
    _navigationViews = [
      NavigationIconView(
          title: '翼信',
          icon: const IconData(0xe60a, fontFamily: Constants.IconFontFamily),
          activeIcon:
              const IconData(0xe60a, fontFamily: Constants.IconFontFamily)),
      NavigationIconView(
          title: '通讯录',
          icon: const IconData(0xe605, fontFamily: Constants.IconFontFamily),
          activeIcon:
              const IconData(0xe604, fontFamily: Constants.IconFontFamily)),
      NavigationIconView(
          title: '智慧屏',
          icon: const IconData(0xe919, fontFamily: Constants.IconFontFamily),
          activeIcon:
              const IconData(0xe919, fontFamily: Constants.IconFontFamily)),
      NavigationIconView(
          title: '我的',
          icon: const IconData(0xe67b, fontFamily: Constants.IconFontFamily),
          activeIcon:
              const IconData(0xe66a, fontFamily: Constants.IconFontFamily)),
    ];
    // 初始化显示当前对应页面
    _pageController = PageController(initialPage: _currentIndex);
    _pages = [
      // 首页
      ConversationPage(),
      // 通讯录
      ContactsPage(),
      // 鲲鹏
      KunPengPage(),
      Container(
        color: Colors.blue,
        child: Center(
          child: Text('我的',
              style: TextStyle(
                  color: Color(AppColors.AppBarPopupMenuTextColor),
                  fontWeight: FontWeight.bold)),
        ),
      ),
    ];
  }

  // 构建添加按钮的菜单项布局
  _buildPopupMenuItem(int iconName, String title) {
    return Row(
      children: <Widget>[
        Icon(
          IconData(iconName, fontFamily: Constants.IconFontFamily),
          size: 18.0,
          color: const Color(AppColors.AppBarPopupMenuTextColor),
        ),
        Container(
          width: 12.0,
        ),
        Text(
          title,
          style: TextStyle(
            color: const Color(AppColors.AppBarPopupMenuTextColor),
            fontSize: 16.0,
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
      statusBarColor: Colors.transparent,
    ));
    final BottomNavigationBar botNavBar = BottomNavigationBar(
      fixedColor: Color(AppColors.TabIconActive),
      items: _navigationViews.map((NavigationIconView view) {
        return view.item;
      }).toList(),
      currentIndex: _currentIndex,
      type: BottomNavigationBarType.fixed,
      onTap: (int index) {
        // 修改_currentIndex的值,放在setState中会重绘当前状态值所带来的ui变化
        setState(() {
          _currentIndex = index;

          // 绑定PageView与TabBar的关联，并且可以调节动画的滑动时间`Duration(milliseconds: 200)`为动画200ms,curve为动画的曲线速度:可以使用预定义`Curves.easeInOut`
          _pageController.animateToPage(_currentIndex,
              duration: Duration(milliseconds: 10), curve: Curves.easeInOut);
        });
        // print('点击的是第$index个tab');
      },
    );

    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          // elevation层级 去掉标题头下的阴影
          elevation: 0.0,
          title: Text(
            '翼信',
            style: TextStyle(
              color: Color(AppColors.AppBarTextColor),
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
          ),
          actions: [
            // IconButton(
            //   icon: Icon(Icons.add),
            //   color: Color(AppColors.AppBarTextColor),
            //   onPressed: () {
            //     print('显示了加号按钮');
            //   },
            // )
            PopupMenuButton(
              icon: Icon(
                const IconData(0xe618, fontFamily: Constants.IconFontFamily),
                color: Color(AppColors.AppBarTextColor),
                size: 20.0,
              ),
              // 二级菜单点击事件
              onSelected: (ActionItems selected) {
                print('点击的是$selected');
              },
              itemBuilder: (BuildContext context) {
                return <PopupMenuItem<ActionItems>>[
                  PopupMenuItem(
                    child: _buildPopupMenuItem(0xe60a, '发起群聊'),
                    value: ActionItems.GROUP_CHAT,
                  ),
                  PopupMenuItem(
                    child: _buildPopupMenuItem(0xe6ce, '添加好友'),
                    value: ActionItems.ADD_FRIEND,
                  ),
                  PopupMenuItem(
                    child: _buildPopupMenuItem(0xe71d, '扫一扫'),
                    value: ActionItems.QR_SCAN,
                  ),
                  PopupMenuItem(
                    child: _buildPopupMenuItem(0xe72e, '收付款'),
                    value: ActionItems.PAYMENT,
                  )
                ];
              },
            ),
          ],
          centerTitle: true,
        ),
        preferredSize: Size.fromHeight(50.0),
      ),
      body: PageView.builder(
        // 每一页需要显示的页面内容
        itemBuilder: (BuildContext context, int index) {
          return _pages[index];
        },
        controller: _pageController,
        // 静止左右滑动
        physics: NeverScrollableScrollPhysics(),
        itemCount: _pages.length,
        // 页面发生变化时的回调函数
        onPageChanged: (int index) {
          setState(() {
            _currentIndex = index;
          });
          // print('当前显示的是第$index页');
        },
      ),
      bottomNavigationBar: botNavBar,
    );
  }
}
